var Recommend = require('../../api/recommend')
var Rank = require('../../api/rank')
var Search = require('../../api/search')
var Song = require('../../api/song')
const perpage = 20
const TYPE_SINGER = 'singer'

//获取应用实例
var app = getApp()
var list = []

Page({
  data: {
      showInput: false,
      // loadingData: false, //数据是否正在加载中，避免用户瞬间多次下滑到底部，发生多次数据加载事件
      hasMore: true, //是否显示加载更多
      showSinger: true, //显示歌手
      page: 1, //搜索结果 默认返回1页
      result: [], //搜索结果 默认空数组
      hotKey: [],
      motto: 'Hello World',
      userInfo: {},
      hasUserInfo: false,
      canIUse: wx.canIUse('button.open-type.getUserInfo'),
      tabList:["推荐音乐","热歌榜","搜索"],
      currentTab:0,
      slider:[],
      recommList: [],
      topList: [],
      indicatorDots: true,
      autoplay: true,
      circular:true,
      interval:2000,
      duration: 500,
      inputValue:'',
      searchHistory:[],
      timer:false
    },

//点击搜索列表的其中一项，保存当前搜索的关键词到storage
  saveHistory:function(e){
    var that = this
    // 把当前点击的歌曲插入到playlist播放列表中
    var song = e.target.dataset.item
    var playlist =  app.globalData.playList
    var currentSong = app.globalData.playList[app.globalData.currentIndex]
    //查找当前要插入的歌曲是否已经在播放列表中
    var fpIndex = playlist.findIndex((item)=>{
      return item.id === song.id
    })
    //当前歌曲的索引+1
    app.globalData.currentIndex = app.globalData.currentIndex+1
    //插入一首歌
    app.globalData.playList.splice(app.globalData.currentIndex, 0, song)
    //如果播放列表中已经包含这首歌
    if(fpIndex > -1){
      if (app.globalData.currentIndex > fpIndex){
        app.globalData.playList.splice(fpIndex,1)
        app.globalData.currentIndex--; 
      } else{
        app.globalData.playList.splice(fpIndex+1,1)
      }
    }
    //原始列表
//获取当前要插入的歌曲在sequencelist中的位置，首先找到当前播放歌曲在列表中的位置 然后+1
    var seqlist = app.globalData.sequenceList;
    var index = seqlist.findIndex((item)=>{
      return item.id === currentSong.id
    })
    let currentSeIndex = index+1 //准备插入的位置
    //查找要插入的歌曲是否已存在与列表中
    let fsIndex = app.globalData.sequenceList.findIndex((item) => {
      return item.id === song.id
    })
    app.globalData.sequenceList.splice(currentSeIndex, 0, song)
    app.globalData.playlist = app.globalData.sequenceList
    if (fsIndex > -1){
      if (currentSeIndex > fsIndex){
        app.globalData.sequenceList.splice(fsIndex,1)
      }else{
        app.globalData.sequenceList.splice(fsIndex+1,1)
      }
    }
    wx.navigateTo({
        url: '../play/play'
      })

    //查找 list 中是否已经有要插入的关键词
    var ss = list.find((item) => {
      return item == that.data.inputValue
    })
    // 判断list最大长度为5，小于5的时候，并且不重复插入的情况下，插入到第一位
    if(list.length < 5){
        if (!ss) {
          list.unshift(that.data.inputValue)
        }
    }else{
      //list的长度大于5时，删除最后一位，在第一位插入新值
      list.pop();
      list.unshift(that.data.inputValue)
    }
    that.setData({ searchHistory: list })
    wx.setStorage({
      key: 'search',
      data: list
    })
  },
  //删除一条历史记录
  delOneHistory: function(e){
    var q = e.target.dataset.v;
    let searches = wx.getStorageSync('search')
    var serRes = searches.findIndex((item)=>{
      return item == q
    })
    searches.splice(serRes,1)

    wx.setStorage({
      key: 'search',
      data: searches
    })
    this.setData({ searchHistory: searches })
  },
  //scrollview 滚动到底部时触发
//上滑加载更多
  scrollToLower: function (e) {
    this.searchMore()
  },
  //加载更多数据
  searchMore(){
    // var loadingData = this.data.loadingData
    // if(loadingData){
    //   return;
    // }
    // this.setData({loadingData: true})
    if(!this.data.hasMore){
      return
    }
    wx.showLoading({
      title: '数据加载中...',
    });
    setTimeout(function(){
      wx.hideLoading();
    },500);

    
   this.data.page++
    Search.search(this.data.inputValue, this.data.page, this.data.showSinger, perpage, this.searchResultMore );
  },
  searchResultMore(res){
    if (res.code === 0) {
      var r = this.data.result.concat(this._genResult(res.data))
      this.setData({ result: r})
      // this.data.result = this.data.result.concat(this._genResult(res.data))
      this._checkMore(res.data)
    }
    
  },
  _checkMore(data){
    const song = data.song
    if(!song.list.length || (song.curnum +(song.curpage-1)*perpage)>=song.totalnum){
      this.setData({hasMore: false})
      console.log('暂无数据')
    }
  },
    // 删除搜索框的内容
  delKey: function(e){

    this.setData({
      inputValue: '',
      result: [],
      showInput:false
    })
    clearTimeout(this.data.timer);
  },
  //键盘输入时触发
  bindKeyInput: function(e){
    this.setData({ inputValue: e.detail.value })
    if(!this.data.inputValue){
      clearTimeout(this.data.timer);
      this.setData({ showInput: false})
      return;
    }
    this.setData({ page: 1 })
    this.throttle(Search.search, 500)(this.data.inputValue, 1, this.data.showSinger, perpage, this.searchResult)

  },
  searchResult(res){
    this.setData({hasMore: true})
    if(res.code === 0){
      this.setData({
        result: this._genResult(res.data)
      })
      
      this.setData({ showInput: true })
      this._checkMore(res.data)
    }
   
  },
  _genResult(data){
    let ret = []
    if (data.zhida && data.zhida.singerid) {
      ret.push({ ...data.zhida, ...{ type: TYPE_SINGER } })
    }
    if(data.song){
     
      ret = ret.concat(this._normalizeSongs(data.song.list))
    }
    return ret
  },
  _normalizeSongs(list){
    let ret = []
    list.forEach((musicData) => {
      if (musicData.songid && musicData.albummid) {
        ret.push(Song.createSong(musicData))
      }
    })
    return ret
  },
  //点击热门搜索词 显示搜索列表
  addQuery: function(e){
    this.setData({ inputValue: e.currentTarget.dataset.item, page: 1 })
    if(!this.data.inputValue){
      clearTimeout(this.data.timer);
      this.setData({showInput: false})
      return
    }
      this.throttle(Search.search, 500)(this.data.inputValue, 1, this.data.showSinger, perpage, this.searchResult)
    // Search.search(this.data.inputValue, 1, this.data.showSinger, 20, this.searchResult);
  },
  //事件处理函数
  // 切换tab
  switchTab:function(e){
    var that = this;
    that.blur();
    if (this.data.currentTab === e.target.dataset.id){
      return false;
    } else {
      that.setData({
        currentTab: e.target.dataset.id
      })

    }
  },
  changeIndicatorDots: function (e) {
    this.setData({
      indicatorDots: !this.data.indicatorDots
    })
  },
  changeAutoplay: function (e) {
    this.setData({
      autoplay: !this.data.autoplay
    })
  },
  intervalChange: function (e) {
    this.setData({
      interval: e.detail.value
    })
  },
  durationChange: function (e) {
    this.setData({
      duration: e.detail.value
    })
  },
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function () {
    var that = this;
      // if (app.globalData.userInfo) {
      //   this.setData({
      //     userInfo: app.globalData.userInfo,
      //     hasUserInfo: true
      //   })
      // } else if (this.data.canIUse){
      //   // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      //   // 所以此处加入 callback 以防止这种情况
      //   app.userInfoReadyCallback = res => {
      //     this.setData({
      //       userInfo: res.userInfo,
      //       hasUserInfo: true
      //     })
      //   }
      // } else {
      //   // 在没有 open-type=getUserInfo 版本的兼容处理
      //   wx.getUserInfo({
      //     success: res => {
      //       app.globalData.userInfo = res.userInfo
      //       this.setData({
      //         userInfo: res.userInfo,
      //         hasUserInfo: true
      //       })
      //     }
      //   })
      // }
    Recommend.getRecommend(that.initPageData);
    Recommend.getDiscList(that.initDiscList);
    Rank.getTopList(that.initTopList);
    Search.getHotKey(that.initHotKey);
    that.openHistorySearch();
  },
  openHistorySearch:function(){
    this.setData({
      searchHistory: wx.getStorageSync('search') || []
    })
  },
  initHotKey:function(data){
    var self = this;
    if(data.code === 0){
      self.setData({
        hotKey: data.data.hotkey.slice(0,10)
      })
    }
  },
  initPageData: function(data){
    var self = this;
    if(data.code === 0){
      self.setData({
        slider:data.data.slider
      })
    
    }
  },
  initDiscList:function(data){
    var self = this;
    if(data.code === 0){
      self.setData({
        recommList:data.data.list
      })

    }
  },
  initTopList: function(data){
    var self = this;
    if (data.code == 0) {
      self.setData({
        topList: data.data.topList
      })
    }
  },
  topListTap: function (e){
    var _item = e.currentTarget.dataset.id;
    // 设置全局变量.保存了一个对象进去
    app.globalData.topList = _item;
    wx.navigateTo({
      url: '../toplist/toplist'
    })
  },
  getUserInfo: function(e) {
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  //截流函数
  throttle: function(func, delay) {
    var that = this
    return function (...args) {
      
      if (that.data.timer) {
        clearTimeout(that.data.timer)
      }
      var timer = setTimeout(() => {
        func.apply(this, args)
      }, delay)

      that.setData({timer: timer})
    }
  },
  //搜索框失去焦点
  blur(){
    this.setData({
      inputValue: '',
      result: [],
      showInput: false
    })
    clearTimeout(this.data.timer);
  }

})
